/**
    Copyright (C) 2012 Guido Ludwig

    This file is part of JATT.
	http://code.google.com/p/jatt/

    JATT is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.guidoludwig.jatt.chain.commands;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import de.guidoludwig.jatt.JATT;
import de.guidoludwig.jatt.chain.JATTContext;
import de.guidoludwig.jatt.chain.commands.config.LastFMConfig;
import de.guidoludwig.jatt.util.ArtworkFilenameFilter;
import de.guidoludwig.jatt.util.AudioInfo;
import de.umass.lastfm.Album;
import de.umass.lastfm.ImageSize;

/**
 * @author Guido Ludwig
 */
public class LastFMArtworkCommand extends JATTCommand<LastFMConfig> {

	private static final String API_KEY = "b63a7a8ce739138920f8ce20b12c9ec4";

	private static final String MARKER = ".LASTFM.";

	@Override
	protected boolean execute0(JATTContext context) {
		if (context.hasFolderImage() && getConfig().isSkipIfImageExists()) {
			return false;
		}
		AudioInfo info = context.getFirst();
		if (info == null) {
			return false;
		}
		if (!info.isArtistAndAlbumTagged()) {
			JATT.debug("Files not correctly tagged with artist and album");
			return false;
		}

		Album a = Album.getInfo(info.getArtist(), info.getAlbum(), API_KEY);
		if (a == null || a.availableSizes() == null
				|| a.availableSizes().isEmpty()) {
			JATT.debug("LastFM : No result for " + info.getArtist()
					+ " - " + info.getAlbum());
			return false;
		}
		List<String> urls = new ArrayList<String>();
		for (ImageSize size : ImageSize.values()) {
			try {
				String imageURL = a.getImageURL(size);
				JATT.debug("LastFM URL : " + size + " :" + imageURL);
				if (imageURL != null && imageURL.length() > 0 && !urls.contains(imageURL)) {
					File out = saveImage(context, size, imageURL);
					urls.add(imageURL);
					context.addToAlternativeImages(out);
				}
			} catch (Exception e) {
				JATT.error(e);
			}
		}
		return false;
	}

	public File saveImage(JATTContext context, ImageSize size, String imageUrl)
			throws IOException, InterruptedException {
		URL url = new URL(imageUrl);
		String extension = "";
		int last = imageUrl.lastIndexOf('.');
		if (last > 0) {
			extension = imageUrl.substring(last);
		}
		InputStream is = url.openStream();
		String filename = ArtworkFilenameFilter.FOLDER_PREFIX + MARKER + size.name()
				+ extension;
		File out = new File(getImageDiretory(context),filename);
		OutputStream os = new FileOutputStream(out);

		byte[] b = new byte[2048];
		int length;
		while ((length = is.read(b)) != -1) {
			os.write(b, 0, length);
		}
		is.close();
		os.close();
		return out;
	}
	
	private File getImageDiretory(JATTContext context) {
		return getConfig().isWriteToAlbumFolder() ? context.getDirectory() : context.getWorkingDirectory();
	}

}
